import Jwt from '../utils/Jwt'

const jwt = new Jwt()
export default async function checkToken(ctx, next) {
    if (/login|register/.test(ctx.request.url)) {
        return await next()
    } else {
        const token = ctx && ctx.request && ctx.request.headers && ctx.request.headers.token
        try {
            const res = await jwt.verifyToken(token)
            if (res) {
                ctx.tokenData = {
                    token,
                    userid: res
                }
                return await next()
            } else {
                ctx.status = 401
                ctx.body = '请登录！'
            }
        } catch (e) {
            console.error(e)
            ctx.status = 401
            ctx.body = '请登录！'
        }
    }
}
